#include "im_rtx_jni_sniff_service_RemoteSniff.h"
#include "process.h"

/*
 * Class:     im_rtx_jni_sniff_service_RemoteSniff
 * Method:    injectProcess
 * Signature: (ILim/rtx/jni/sniff/bean/InjectParam;)V
 */
JNIEXPORT jboolean JNICALL Java_im_rtx_jni_sniff_service_RemoteSniff_injectProcess
  (JNIEnv *env, jobject, jint pid, jstring module){
	DWORD dwExitCode = 0;
	return loadLibraryRemote(pid, (char*) env->GetStringUTFChars(module, 0), &dwExitCode);
}

/*
 * Class:     im_rtx_jni_sniff_service_RemoteSniff
 * Method:    freeProcess
 * Signature: (ILim/rtx/jni/sniff/bean/InjectParam;)V
 */
JNIEXPORT jboolean JNICALL Java_im_rtx_jni_sniff_service_RemoteSniff_freeProcess
  (JNIEnv *env, jobject, jint pid, jstring module)
{
	DWORD dwExitCode = 0;
	return freeLibraryRemote(pid, (char*) env->GetStringUTFChars(module, 0), &dwExitCode);
}

/*
 * Class:     im_rtx_jni_sniff_service_RemoteSniff
 * Method:    queryProcessList
 * Signature: ()Ljava/util/List;
 */
JNIEXPORT jobject JNICALL Java_im_rtx_jni_sniff_service_RemoteSniff_queryProcessList
  (JNIEnv *env, jobject thiz)
{
	jclass listClass = env->FindClass("java/util/ArrayList");
	jmethodID listCtorMid = env->GetMethodID(listClass, "<init>", "()V");
	jobject listObject = env->NewObject(listClass, listCtorMid);


	jclass pinfoClass = env->FindClass("im/rtx/jni/sniff/bean/ProcessInfo");
	jmethodID setPathMid = env->GetMethodID(pinfoClass, "setPath", "(Ljava/lang/String;)V");
	jmethodID setPidMid = env->GetMethodID(pinfoClass, "setPid", "(I)V");
	jmethodID addMid = env->GetMethodID(listClass, "add", "(Ljava/lang/Object;)Z");

	map<int, string> processMap;
	queryProcessList(processMap);

	map<int, string>::iterator it;
	for(it = processMap.begin(); it != processMap.end(); it++){
		jint pid = (*it).first;
		jstring path = env->NewStringUTF((*it).second.c_str());
		jobject pinfo = env->AllocObject(pinfoClass);
		env->CallObjectMethod(pinfo, setPathMid, path);
		env->CallObjectMethod(pinfo, setPidMid, pid);
		env->CallObjectMethod(listObject, addMid, pinfo);
	}

	return listObject;
}